<template>
  <div class="a3-page">
    <div class="tool-view" :style="{ width: tableW }">
      <div class="tool-l">
        <!-- <span>站点</span> -->
        <n-select
          placeholder="选择站点名称"
          style="width: 6.25rem"
          :consistent-menu-width="false"
          :to="false"
          v-model:value="params.modelId"
          :options="stationList"
          @update:value="GetAllStationInfoFun"
        />
        <!-- <span>OP</span> -->
        <n-select
          placeholder="选择OP属性"
          style="width: 6.25rem"
          :consistent-menu-width="false"
          :to="false"
          v-model:value="params.stationId"
          :options="OPList"
        />
        <!-- <span>编码</span> -->
        <n-select
          placeholder="选择设备编码"
          style="width: 6.25rem"
          :consistent-menu-width="false"
          :to="false"
          v-model:value="devicecode"
          :options="deviceList"
        />
        <!-- <span>产品</span> -->
        <n-select
          placeholder="选择产品名称"
          style="width: 6.25rem"
          :consistent-menu-width="false"
          :to="false"
          v-model:value="params.productName"
          :options="productNameList"
          @update:value="GetProductSNListFun"
        />
        <!-- <span>SN</span> -->
        <n-select
          placeholder="选择SN码"
          style="width: 6.25rem"
          :consistent-menu-width="false"
          :to="false"
          v-model:value="params.productSN"
          :options="productSNList"
        />
        <!-- <span>时间</span> -->
        <div class="pcker-view">
          <div class="mask" @click="show = true"></div>
          <n-config-provider :locale="zhCN" :date-locale="dateZhCN">
            <n-date-picker
              style="width: 345px"
              v-model:value="range"
              type="datetimerange"
              clearable
              :show="show"
              :to="false"
              @update:formatted-value="timeChange"
              :is-date-disabled="disablePreviousDate"
              @confirm="show = false"
              @blur="show = false"
            />
          </n-config-provider>
        </div>
        <n-button
          style="margin-left: 12px"
          type="success"
          :disabled="!isQuery"
          @click="GetMobproductDataExFun"
        >
          查询
        </n-button>
      </div>
    </div>
    <div class="table-view">
      <div class="select-view">
        <div class="view">
          <n-select
            placeholder="选择参数"
            class="n-select"
            :show-arrow="false"
            style="width: 10rem"
            :to="false"
            :options="titleList"
            @update:value="GetMobproductDataOneFun"
          />
        </div>
      </div>
      <div class="top-view">
        <Polyline :data="echarlsList" />
        <div class="text-view">
          <div class="text">
            {{ remark }}
          </div>
        </div>
      </div>
      <div ref="container" class="bottom-view" :class="showTop ? '' : 'show'">
        <div
          v-if="data.length > 0"
          class="line"
          :class="showTop ? 'top' : ''"
          @click="showTopFun"
        >
          <icons class="icon" name="top" />
        </div>
        <n-data-table
          :style="{
            transform: 'scale(0.6)',
            'transform-origin': 'top left',
            width: tableW1,
          }"
          remote
          :loading="loading"
          :data="data"
          :columns="columns"
          :single-line="false"
          :single-column="true"
          :pagination="pagination"
          :scroll-x="scrollX"
          :max-height="height"
          @update:page="handlePageChange"
        />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, ref, h } from "vue";
import { useRoute } from "vue-router";
import Polyline from "@/components/Echarts/Polyline.vue"; //折线
import { today } from "@/tools/radom";
import {
  GetAllStationInfo,
  GetProductNameList,
  GetProductSNList,
  GetPageA2Name,
  GetMobproductDataEx,
  GetMobproductDataOne,
  GetEMailType,
  GetMobdevicelsBydevicetype,
  GetMobprambydevicecode,
} from "@/server";
import { zhCN, dateZhCN } from "naive-ui";
import { useAppStore } from "@/store/modules/user";
// const modelId = computed(() => route.params.id);
const store = useAppStore();
const openMore = ref(false);
const stationList = ref([]) as any; //站台列表
const OPList = ref([]) as any; //站台列表
const range = ref<[number, number]>([Date.now(), Date.now()]);
const params = ref({
  // modelId: "",
  // stationId: 0,
  // productName: "",
  // productSN: "",
  startTime: today(),
  endTime: today(),
}) as any;
const emialParams = ref({
  emailAddress: "",
  password: "",
  checkPassword: "",
}) as any;
const pagination = ref({
  page: 1,
  pageCount: 1,
  pageSize: 20,
  pageSlot: 7,
});
const senParams = ref({
  mailTo: "",
  mailSubject: "",
  filePath: "",
});
const show = ref(false);
const disablePreviousDate = (ts: number) => {
  return ts > Date.now();
};
const route = useRoute();
const devicetype = computed(() => route.params.remark);
const devicecode = ref(null) as any;
const emailOptions = ref([]) as any;
const openDelDialog = ref(false);
const showTop = ref(false);
const data = ref([]) as any;
const columns = ref() as any;
const scrollX = ref(2000);
const loading = ref(false);
const productNameList = ref([]) as any; //产品名称列表;
const productSNList = ref([]) as any; //产品SN码列表
const titleList = ref([]) as any; //参数
const closeWin = () => {
  openDelDialog.value = false;
  openMore.value = false;
};
const setType = ref(0);
const timeChange = (e: any) => {
  params.value.startTime = e[0];
  params.value.endTime = e[1];
};
const showTopFun = () => {
  showTop.value = !showTop.value;
  if (showTop.value) {
    if (titleList.value.length > 0) {
      // GetMobproductDataOneFun(titleList.value[0].value);
    }
  }
  setTimeout(() => {
    updateHeight();
  }, 300);
};
const isQuery = computed(() => {
  const { modelId, stationId, productName, productSN } = params.value;
  return modelId && stationId && productName && productSN;
});
const handlePageChange = (curent: number) => {
  console.log(curent);
  pagination.value.page = curent;
  GetMobproductDataExFun();
};
const height = ref(0);
const container = ref(null) as any;
const updateHeight = () => {
  if (container.value) {
    const containerHeight = container.value.offsetHeight;
    height.value = containerHeight + containerHeight * 0.35;
  }
};
const tableW = ref("100%");
const tableW1 = ref("100%");
onMounted(() => {
  // 获取页面宽度
  const pageWidth = window.innerWidth;
  // 计算百分比
  const percentage = (pageWidth / (pageWidth * 0.7)) * 100;
  const percentage1 = (pageWidth / (pageWidth * 0.6)) * 100;
  tableW.value = percentage + "%";
  tableW1.value = percentage1 + "%";
  updateHeight();
  window.addEventListener("resize", updateHeight);

  // Cleanup listener on component unmount
  return () => {
    window.removeEventListener("resize", updateHeight);
  };
});

const lock = ref(false);
const unLock = () => {
  setTimeout(() => {
    lock.value = false;
  }, 1000);
};
//查询数据
const GetMobproductDataExFun = async () => {
  loading.value = true;
  if (lock.value) {
    return false;
  }
  lock.value = true;
  const param = {
    productsn: params.value.productSN,
    opcode: params.value.stationId,
    devicecode: devicecode.value,
    devicetype: devicetype.value,
    page: pagination.value.page,
    pagesize: 20,
    begindate: params.value.startTime,
    enddate: params.value.endTime,
  };
  const res: any = await GetMobproductDataEx(param);
  if (res.result.isSuccess) {
    loading.value = false;
    columns.value = res.result.header.map((e: any, index: number) => {
      if (e.key === "id") {
        e.width = 100;
        e.fixed = "left";
        e.titleAlign = "center";
        e.align = "center";
      } else {
        e.width = 140;
        e.titleAlign = "center";
        e.align = "center";
        e.ellipsis = {
          tooltip: true,
        };
      }
      return e;
    });
    //因为value很多一样的所以
    const arr = columns.value
      .filter((e: any) => e.remark)
      .map((e: any) => {
        return { value: generateRandomString() + e.remark, label: e.title };
      });

    // 使用 Set 进行去重 // 使用 Set 去除重复项，然后通过 Array.from 转回数组
    titleList.value = arr;
    //  Array.from(
    //   new Set(arr.map((obj: any) => JSON.stringify(obj))),
    //   (jsonString: any) => JSON.parse(jsonString) as any
    // );

    scrollX.value = columns.value.length * 140 - 80;
    const list = res.result.result;
    const viewmodels = list.map((e: any) => {
      const list1 = e.viewmodels;
      const list2 = e.viewmodelsplc;
      delete e.viewmodels;
      delete e.viewmodelsplc;
      const obbj: any = e;
      for (let index = 0; index < list1.length; index++) {
        const element = list1[index];
        obbj[element.indicator] = element.parmvalue;
      }
      for (let index = 0; index < list2.length; index++) {
        const element = list2[index];
        obbj[element.indicator] = element.parmvalue;
      }
      return obbj;
    });

    data.value = viewmodels;
    pagination.value.pageCount = Math.ceil(
      res.result.otherResult / param.pagesize
    );
    if (data.value.length === 0) {
      store.info("未查询到数据"); // 错误提示
    }
    unLock();
  } else {
    unLock();
    loading.value = false;
    store.error(res.result.message); // 错误提示
  }
};
const remark = ref("");
const GetMobprambydevicecodeFun = async () => {
  const res: any = await GetMobprambydevicecode({
    devicecode: devicecode.value,
    indicator: deviceInfo.value.indicator,
    parmtype: deviceInfo.value.parmtype,
  });
  if (res.result.isSuccess) {
    remark.value = res.result.result.remark;
  } else {
    store.error(res.result.message); // 错误提示
  }
};
function generateRandomString() {
  // 生成数字和字母的字符集
  const characters =
    "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

  // 初始化结果字符串
  let result = "";

  // 随机生成10位字符
  for (let i = 0; i < 10; i++) {
    const randomIndex = Math.floor(Math.random() * characters.length);
    result += characters.charAt(randomIndex);
  }

  return result;
}
//获取所有站点配置
const GetAllStationInfoFun = async () => {
  const res: any = await GetAllStationInfo({
    modelId: params.value.modelId,
  });
  if (res.result.isSuccess) {
    OPList.value = res.result.result.map((e: any) => {
      e.value = e.stationName;
      e.label = e.stationName;
      return e;
    });
  } else {
    store.error(res.result.message); // 错误提示
  }
};
const echarlsList = ref([]) as any;
const deviceInfo = ref({ indicator: "", parmtype: "" });
const GetMobproductDataOneFun = async (modey: string) => {
  const titleData = titleList.value.find((e: any) => e.value === modey);
  deviceInfo.value.indicator = titleData.label;
  deviceInfo.value.parmtype = titleData.value.substring(10);
  const param = {
    productsn: params.value.productSN,
    opcode: params.value.stationId,
    devicecode: devicecode.value,
    devicetype: devicetype.value,
    indicator: deviceInfo.value.indicator,
    parmtype: deviceInfo.value.parmtype,
    page: 1,
    pagesize: 100,
  };
  const res: any = await GetMobproductDataOne(param);
  if (res.result.isSuccess) {
    echarlsList.value = res.result.result;
  } else {
    store.error(res.result.message); // 错误提示
  }
  GetMobprambydevicecodeFun();
};
//获取产品名称列表
const GetProductSNListFun = async () => {
  const res: any = await GetProductSNList({
    productName: params.value.productName,
  });
  if (res.result.isSuccess) {
    productSNList.value = res.result.result.map((e: any) => {
      return { value: e, label: e, id: e };
    });
  } else {
    store.error(res.result.message); // 错误提示
  }
};
//获取产品名称列表
const GetProductNameListFun = async () => {
  const res: any = await GetProductNameList({});
  if (res.result.isSuccess) {
    productNameList.value = res.result.result.map((e: any) => {
      return { value: e, label: e, id: e };
    });
  } else {
    store.error(res.result.message); // 错误提示
  }
};

//获取初始化数据1
const GetPageA2NameFun = async () => {
  const res: any = await GetPageA2Name({});
  if (res.result.isSuccess) {
    stationList.value = res.result.result.map((e: any) => {
      e.value = e.modelId;
      e.label = e.name;
      return e;
    });
  } else {
    store.error(res.result.message); // 错误提示
  }
};
//获取初始化数据1
const GetEMailTypeFun = async () => {
  const res: any = await GetEMailType({});
  if (res.result.isSuccess) {
    emailOptions.value = res.result.result.map((e: any) => {
      return { value: e, label: e };
    });
  } else {
    store.error(res.result.message); // 错误提示
  }
};
GetEMailTypeFun();
//获取设备类型
const deviceList = ref([]) as any;
const GetMobdevicelsBydevicetypeFun = async () => {
  const res: any = await GetMobdevicelsBydevicetype({
    devicetype: devicetype.value,
  });
  if (res.result.isSuccess) {
    deviceList.value = res.result.result.map((e: any) => {
      return { value: e.devicecode, label: e.devicecode };
    });
  } else {
    store.error(res.result.message); // 错误提示
  }
};
GetMobdevicelsBydevicetypeFun();
GetPageA2NameFun();
GetProductNameListFun();
</script>

<style lang="less" scoped>
.a3-page {
  width: 100vw;
  height: calc(100vh - 2.4rem);
  overflow: hidden;
  background: #ffffff;
  .tool-view {
    position: relative;
    z-index: 21;
    padding: 0.3rem 0;
    transform: scale(0.7);
    transform-origin: top left;
    width: 100%;
    display: flex;
    align-items: center;
    background: #e3e3e3;
    backdrop-filter: blur(32px);

    .tool-l {
      display: flex;
      align-items: center;
      .pcker-view {
        position: relative;
        .mask {
          position: absolute;
          z-index: 1;
          width: 100%;
          height: 100%;
        }
      }
      span {
        font-size: 1rem;
        font-family: PingFangSC, PingFang SC;
        font-weight: 500;
        color: #1c262d;
        margin: 0 0.5rem;
      }
    }
  }
  .table-view {
    position: relative;
    height: calc(100% - 3rem);
    margin-top: -0.8rem;
    .select-view {
      padding: 0.5rem 0;
      .view {
        position: relative;
        z-index: 10;
        margin: auto;
        width: 10rem;
        height: 32px;
        background: #5d6a73;
        box-shadow: 0px 0px 1px 0px rgba(0, 0, 0, 0.08),
          0px 1px 3px 0px rgba(25, 15, 15, 0.07),
          0px 3px 5px 0px rgba(0, 0, 0, 0.05);
        transform: scale(0.8);
        .n-select {
          :deep(.n-base-selection-label) {
            background: none;
            .n-base-selection-input {
              color: #ffffff;
            }
          }
        }
      }
    }
    .top-view {
      overflow: hidden;
      height: calc(90% - 4rem);
      display: flex;
      align-items: center;
      justify-content: center;
      .text-view {
        margin-right: 1rem;
        position: relative;
        width: 40%;
        height: 100%;
        background: #f9f9f9;
        border-radius: 3px;
        .text {
          padding: 10px;
          text-align: left;
        }
      }
    }
    .line {
      display: flex;
      align-items: center;
      justify-content: center;
      &.top {
        transform: rotate(0deg);
      }
      transform: rotate(180deg);
      color: #ffffff;
      background: #dbdbdb;
      height: 0.8rem;
      position: relative;
      .icon {
        position: absolute;
      }
    }
    .bottom-view {
      z-index: 20;
      &.show {
        height: 100%;
      }
      background: #ffffff;
      width: 100%;
      position: absolute;
      height: 10%;
      bottom: 0;
      transition: height 0.3s;
    }
  }
  :deep(.n-data-table__pagination) {
    padding-right: 1.5rem;
  }
  :deep(.n-date-panel) {
    transform: scale(0.95);
    transform-origin: top left;
  }
}
</style>
